#include "GamePage.h"
#include "GB2ShapeCache-x.h"
#include "config.h"
#include <jni.h>
#include <JniHelper.h>
#include "ODSocket.h"
using namespace cocos2d;
float GamePage::scale = 0.0;
float GamePage::scaleX = 0.0;
float GamePage::scaleY = 0.0;
#define PTM_RATIO 32.0
#define NUMOFBALLS 5
struct SpiriteData
{
	CCSprite * sp;
	CCSprite *lock;
	char * type;
	bool islock;
};
CCScene * GamePage::scene()
{
	CCScene * scene = NULL;
	do 
	{
		scene = new CCScene();
		CC_BREAK_IF(!scene);
		GamePage * gamelayer = GamePage::create();
		CC_BREAK_IF(!gamelayer);
		scene->addChild(gamelayer);
	} while (0);
	return scene;
}
GamePage::GamePage()
{

}
GamePage::~GamePage()
{
	delete world;
	world = NULL;
}
void GamePage::keyBackClicked()
{
	CCDirector::sharedDirector()->end();
}
bool GamePage::init()
{
	bool bRet = false;
	do 
	{
		CC_BREAK_IF(!CCLayer::init());
		winsize = CCDirector::sharedDirector()->getWinSize();
		scaleX = winsize.width/480.0;
		scaleY = winsize.height/800.0;
		scale = scaleX>scaleY?scaleY:scaleX;
		//利用一个shape类得到多边形的fixture
		GB2ShapeCache::sharedGB2ShapeCache()->addShapesWithFile("shapemater.plist");
		setKeypadEnabled(true);
		//初始化物体世界
		initWorld();
		//初始化背景图
		initBackGround();
		//初始化物理边框
		initBoxGround();
		//初始化按钮
		initMenu();
		//初始化加力区域
		initForceRegin();
		//初始化时间条
		initTimeBar();
		
		//初始化分数条
		initScoreBar();
		//初始化触摸笔迹
		initBrush();
		//初始化动画
		initAnimation();
		//初始化调试画图
		initDebugDraw();

		initBalls();
		initLabel();
		//设置每帧刷新
		scheduleUpdate();
		setTouchEnabled(true);
		a = true;
		touchable = true;
		currenttimeofball = 0;
		//initSocket();
		//设置隔一定时间掉落物体
		schedule(schedule_selector(GamePage::initByTime),1,4,0);//-1为无限次掉落

	} while (0);
	return true;
}
void GamePage::onEnter()
{
	CCLayer::onEnter();
	
}
void GamePage::onExit()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCLayer::onExit();
}
void GamePage::registerWithTouchDispatcher()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}
void GamePage::initWorld()
{
	_contactsListener = new MyContactListener();
	b2Vec2 gravity(0,-10);
	world = new b2World(gravity);
	world->SetAllowSleeping(true);
	world->SetContinuousPhysics(true);
	world->SetContactListener(_contactsListener);
}
void GamePage::initBrush()
{
	m_pBrush = CCSprite::create("fire.png");
	m_pBrush->retain();
	m_pBrush->setColor(ccRED);
	m_pBrush->setOpacity(20);
	m_pTarget = CCRenderTexture::create(winsize.width, winsize.height, kCCTexture2DPixelFormat_RGBA8888);
	m_pTarget->retain();
	m_pTarget->setPosition(ccp(winsize.width / 2, winsize.height / 2));
	this->addChild(m_pTarget,1);
}
void GamePage::initLabel()
{
	char scorevalue[20];
	sprintf(scorevalue,"SCORE:  %d",0);
	scorelabel = CCLabelTTF::create(scorevalue,"Cooper Black",20);
	scorelabel->setScale(scale);
	scorelabel->setPosition(ccp(385*scaleX,755*scaleY));
	scorelabel->setColor(ccc3(0,255,0));
	addChild(scorelabel);


	char levelvalue[20];
	sprintf(levelvalue,"%d",current_level);
	levellabel = CCLabelTTF::create(levelvalue,"Cooper Black",30);
	levellabel->setScale(scale);
	levellabel->setPosition(ccp(430*scaleX,30*scaleY));
	addChild(levellabel);
}
void GamePage::initAnimation()
{
	cache = CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFramesWithFile("bomb.plist","bomb.png");
	cache->addSpriteFramesWithFile("booom.plist","booom.png");
	cache->addSpriteFramesWithFile("lighting.plist","lighting.png");
}
void GamePage::initDebugDraw()
{
	debugDraw = new GLESDebugDraw(PTM_RATIO);
	world->SetDebugDraw(debugDraw);
	uint32 flag = 0;
	flag += b2Draw::e_shapeBit;
	debugDraw->SetFlags(flag);
}
bool GamePage::initBackGround()
{
	CCSprite *background = CCSprite::create("bg_04.png");
	bgscalex = 480.0/background->getTextureRect().size.width*scaleX;
	bgscaley = 800.0/background->getTextureRect().size.height*scaleY;
	background->setScaleX(bgscalex);
	background->setScaleY(bgscaley);
	background->setAnchorPoint(ccp(0,0));
	background->setPosition(ccp(0,0));
	addChild(background);
	return true;
}
bool GamePage::initBoxGround()
{
	b2BodyDef grounddef;
	float bg_scalex = 0.0;
	float bg_scaley = 0.0;

	b2Body *groundbody = world->CreateBody(&grounddef);

	b2EdgeShape bodyshape;
	bodyshape.Set(b2Vec2(10.0*scaleX/PTM_RATIO,(40.0)*scaleY/PTM_RATIO),b2Vec2(10.0*scaleX/PTM_RATIO,660*scaleY/PTM_RATIO));
	groundbody->CreateFixture(&bodyshape,0);

	//bodyshape.Set(b2Vec2(20.0*scaleX/PTM_RATIO,(230.0)*scaleY/PTM_RATIO),b2Vec2(170*scaleY/PTM_RATIO,160.0*scaleY/PTM_RATIO));
	//groundbody->CreateFixture(&bodyshape,0);


	bodyshape.Set(b2Vec2(10*scaleY/PTM_RATIO,40.0*scaleY/PTM_RATIO),b2Vec2(470.0*scaleX/PTM_RATIO,40.0*scaleY/PTM_RATIO));
	groundbody->CreateFixture(&bodyshape,0);


	bodyshape.Set(b2Vec2(10.0*scaleX/PTM_RATIO,660.0*scaleY/PTM_RATIO),b2Vec2(470.0*scaleX/PTM_RATIO,(660.0)*scaleY/PTM_RATIO));
	groundbody->CreateFixture(&bodyshape,0);

	//bodyshape.Set(b2Vec2(455.0*scaleX/PTM_RATIO,(230.0)*scaleY/PTM_RATIO),b2Vec2(455.0*scaleX/PTM_RATIO,(730.0)*scaleY/PTM_RATIO));
	//groundbody->CreateFixture(&bodyshape,0);

	bodyshape.Set(b2Vec2(470.0*scaleX/PTM_RATIO,660*scaleY/PTM_RATIO),b2Vec2(470.0*scaleX/PTM_RATIO,(40.0)*scaleY/PTM_RATIO));
	groundbody->CreateFixture(&bodyshape,0);
	return true;
}
bool GamePage::initBalls()
{
	for (int i = 0;i<NUMOFBALLS;i++)
	{
		char path[20];
		int randnum = rand()%kNumOfBallByLevel[current_level]+1;
		//int randnum = 1;
		sprintf(path,"monster_0%d.png",randnum);
		CCSprite *ball = CCSprite::create(path);
		ball->setPosition(ccp(0+(i+3)*50*scaleX,600*scaleY));
		ball->setScale(scale);
		addChild(ball);

		b2BodyDef balldef;
		balldef.type = b2_dynamicBody;
		balldef.position.Set(0+(i+3)*50/PTM_RATIO*scaleX,600/PTM_RATIO*scaleY);


		SpiriteData *sd = new SpiriteData();
		char *name = new char[20];
		sprintf(name,"monster_0%d",randnum);
		sd->sp = ball;
		sd->type = name;
		if(rand()%kLockAppearProperty[current_level] == 1)
		{
			sd->islock = true;
			CCSprite * lock = CCSprite::create("lock.png");
			lock->setVisible(false);
			addChild(lock);
			sd->lock = lock;
		}
		else
		{
			sd->islock = false;
		}
		balldef.userData = sd;

		b2Body *ballbody = world->CreateBody(&balldef);
		
		GB2ShapeCache *sc = GB2ShapeCache::sharedGB2ShapeCache();
		
		
		sc->addFixturesToBody(ballbody, name);
		ball->setAnchorPoint(sc->anchorPointForShape(name));
		
	}
	currenttimeofball++;
	if(currenttimeofball == 4)
	{
		unschedule(schedule_selector(GamePage::initByTime));
		schedule(schedule_selector(GamePage::initByTime),5,-1,0);//-1为无限次掉落
	}
	return true;
}
void GamePage::initSocket()
{


	ODSocket csocket;
	csocket.Init();
	csocket.Create(AF_INET,SOCK_STREAM,0);
	csocket.Connect("192.168.1.230",7880);
	char recvBuf[64] = "\0";
	csocket.Send("xuelang love renyanfei",strlen("hello")+1,0);
	csocket.Recv(recvBuf,64,0);
	CCMessageBox(recvBuf,"receive message");
	csocket.Close();
	csocket.Clean();
}
void GamePage::initScoreBar()
{
	CCSprite *scorebarspirit = CCSprite::create("timeBar.png");
	scorebarspirit->setScaleX(scaleX);
	scorebarspirit->setScaleY(scaleY);


	scorebar = CCProgressTimer::create(scorebarspirit);
	scorebar->setScaleX(scaleX);
	scorebar->setScaleY(scaleY);
	scorebar->setType(kCCProgressTimerTypeBar);
	scorebar->setMidpoint(ccp(0,0));
	scorebar->setBarChangeRate(ccp(1,0));
	scorebar->setPosition(ccp(240*scaleX,700*scaleY));
	scorebar->setPercentage(current_score);
	addChild(scorebar,-1);

}
void GamePage::update(float dt)
{
	int velocityIterations = 8;
	int positionIterations = 1;

	// Instruct the world to perform a single step of simulation. It is
	// generally best to keep the time step and iterations fixed.
	world->Step(dt, velocityIterations, positionIterations);
	//
	for (vector<CCSprite *>::iterator it = spritelist.begin();it!=spritelist.end();it++)
	{
		removeChild(*it,true);
	}
	spritelist.clear();
	for(b2Body *b = world->GetBodyList();b;b = b->GetNext())
	{
		if(b->GetUserData()!=NULL)
		{
			SpiriteData* cs = (SpiriteData *)b->GetUserData();
			//CCSprite *cs = (CCSprite *)b->GetUserData();
			cs->sp->setPosition(ccp(b->GetPosition().x*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
			if (cs->islock)
			{
				cs->lock->setPosition(ccp(b->GetPosition().x*PTM_RATIO,b->GetPosition().y*PTM_RATIO));
				cs->lock->setVisible(true);
			}
			//cs->sp->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));
			

		}
	}
	if(can_line_list.size()>1)
		{
			for (vector<b2Body *>::iterator it = can_line_list.begin();it!=can_line_list.end()-1;it++)
			{
				b2Vec2 first = (*it)->GetPosition();
				b2Vec2 second = (*(it+1))->GetPosition();
				lineTwoPoint(ccp(first.x*PTM_RATIO,first.y*PTM_RATIO),ccp(second.x*PTM_RATIO,second.y*PTM_RATIO));
			}
	    }

}
bool GamePage::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	if(touchable == false)
		return false;
	can_line_list.clear();
	
	CCPoint point = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
	//pointlist.push_back(point);
	
	return true;
}
void GamePage::initByTime(float dt)
{
	initBalls();
	
	if (isLose())
	{
		unschedule(schedule_selector(GamePage::initByTime));
		showLoseLayer();
		touchable = false;
		return;
	}
	
}
void GamePage::showLoseLayer()
{
	CCLayerColor *lose_layer = CCLayerColor::create(ccc4(0,0,0,100));

	CCSprite *lose = CCSprite::create("lose.png");
	lose->setPosition(ccp(240*scaleX,500*scaleY));
	lose->setScale(scale);
	lose_layer->addChild(lose);
	
	CCSprite *agin_sprite = CCSprite::create("agin.png");
	CCSprite *agin_click_sprite = CCSprite::create("agin.png");

	CCMenuItemSprite *agin = CCMenuItemSprite::create(agin_sprite,agin_click_sprite,this,menu_selector(GamePage::agin));
	agin->setPosition(ccp(0*scaleX,-150*scaleY));
	agin->setScale(scale*0.5);
	CCMenu *menu = CCMenu::create();
	menu->addChild(agin);
	lose_layer->addChild(menu);
	
	
	addChild(lose_layer);




}
void GamePage::agin(cocos2d::CCObject *sender)
{
	current_score = 0;
	CCDirector::sharedDirector()->replaceScene(GamePage::scene());
}
bool GamePage::isLose()
{
	int num = 0;
	for (b2Body *b = world->GetBodyList();b;b = b->GetNext())
	{
		if (b->GetUserData()!=NULL)
		{
			num++;
		}
	}
	if (num>=kTotalNumOfBall)
		return true;
	else
		return false;
}
void GamePage::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
	
	//CCLOG("touch moved%d",a++);
	CCPoint start = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
	//myPoint = start;
	//k = true;
	//pointlist.push_back(start);
	isPointInObject(start);
	//CCPoint end = CCDirector::sharedDirector()->convertToGL(pTouch->previousLocationInView());
	//bool isin = isPointInObject(start);
	//bool isfirst = true;
	/*for (vector<CCPoint>::iterator it = pointlist.begin();it!=pointlist.end();it++)
	{
			isPointInObject(*it);
	}*/
	/*m_pTarget->begin();


	float distance = ccpDistance(start, end);
	if (distance > 1)
	{
		int d = (int)distance;
		for (int i = 0; i < d; i++)
		{
			float difx = end.x - start.x;
			float dify = end.y - start.y;
			float delta = (float)i / distance;
			m_pBrush->setPosition(ccp(start.x + (difx * delta), start.y + (dify * delta)));
			m_pBrush->setRotation(rand() % 360);
			float r = (float)(rand() % 50 / 50.f) + 0.25f;
			m_pBrush->setScale(r);
			m_pBrush->setColor(ccc3(CCRANDOM_0_1() * 127 + 128, 255, 255));
			// Use CCRANDOM_0_1() will cause error when loading libtests.so on android, I don't know why.
			m_pBrush->setColor(ccc3(rand() % 127 + 128, 0, 255));
			// Call visit to draw the brush, don't call draw..
			m_pBrush->visit();
		}
	}

	// finish drawing and return context back to the screen
	m_pTarget->end();*/
}
bool GamePage::isPointInObject(cocos2d::CCPoint pt)
{
	for(b2Body * b=world->GetBodyList();b;b = b->GetNext())
	{

		if(b->GetUserData()!=NULL)
		{
			b2Vec2 temp;
			temp.x = pt.x/PTM_RATIO;
			temp.y = pt.y/PTM_RATIO;
			bool isinobject = false;
			//这里一定要注意，要遍历所有的fixture来检测，因为里面有凹多边形，会将其分为几个凸多边形。
			for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
			{
				isinobject = f->TestPoint(temp);
				if (isinobject)
				{
					break;
				}
			}
			if(isinobject)
			{
					//CCSprite *a = CCSprite::create("ball_0.png");
					//b->ApplyLinearImpulse(b2Vec2(0,10),b->GetPosition());
					
					vector<b2Body *>::iterator it = can_line_list.begin();;
					if(can_line_list.size() == 0)
						can_line_list.push_back(b);

					it = find(can_line_list.begin(),can_line_list.end(),b);
					
					if(it == can_line_list.end()&&can_line_list.size()>0)
					{
						vector<b2Body *>::iterator last = can_line_list.end()-1;
						b2Vec2 lastp = (*last)->GetPosition();
						b2Vec2 nowp = b->GetPosition();
						float dis = sqrt((lastp.x-nowp.x)*(lastp.x-nowp.x)+(lastp.y-nowp.y)*(lastp.y-nowp.y));
						if(dis<=120*scale/PTM_RATIO)
						{
							can_line_list.push_back(b);
						}
					}
					return true;
				}
		}
	}
	return false;
}
void GamePage::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
	bool issame = true;
	k = false;
	CCPoint point = CCDirector::sharedDirector()->convertToGL(pTouch->locationInView());
	
	
	if (can_line_list.size()>1)
	{
		int *dispier = new int[can_line_list.size()];
		
		int b = can_line_list.size();
		memset(dispier,0,can_line_list.size()*4);
		char *type = ((SpiriteData *)(*can_line_list.begin())->GetUserData())->type;
		samecount = 1;
		int startpos = 0;
		int endpos = 0;
		char * temp = "";
		int test = 0;
		for (vector<b2Body *>::iterator it = can_line_list.begin();it!=can_line_list.end();it++)
		{
			test++;
			char * currenttype = new char[20];
			//char * lasttype = ((SpiriteData *)(*it)->GetUserData())->type;
			//这里加这个的目的是：如果最后的三个是相同的但是后续如果没有不同的话，if(samecount>=3)就不会执行了。
			if(it == can_line_list.end()-1)
				currenttype = temp;
			else
				currenttype = ((SpiriteData *)(*(it+1))->GetUserData())->type;

			if(!strcmp(currenttype,type))
			{
					//issame = false;
					samecount++;
					endpos++;
			}
			else 	
			{

				type = currenttype;
				setScoreByCount(samecount);
				if(samecount>=3)
				{
					CCPoint temp;
					CCRect lightrect;
					bool isfirstBooom = true;
					bool isfirstLighting = true;
					for(int i = startpos;i<=endpos;i++)
					{
						SpiriteData* cs  = (SpiriteData *)(can_line_list[i])->GetUserData();
						CCSprite *sp = cs->sp;
						if(samecount==3)
						{
							CCSprite *smallbomb;
							smallbomb = CCSprite::create(cache->spriteFrameByName("boom_01.png"));
							smallbomb->setPosition(sp->getPosition());
							addChild(smallbomb);
							CCAnimate *smallbombanimate = getSmallBombAnimation();
							smallbomb->runAction(CCSequence::create(smallbombanimate,CCCallFuncN::create(this,callfuncN_selector(GamePage::smallBombCallBack)),NULL));
	
						}
						else if(samecount==4&&isfirstBooom)
						{

							int mid = (startpos+endpos)/2;
							
							temp.x= can_line_list[mid]->GetPosition().x*PTM_RATIO;
							temp.y = can_line_list[mid]->GetPosition().y*PTM_RATIO;
							//bomblist.insert(map<CCPoint,int>::value_type(temp,samecount));
							
							CCSprite *bigbomb;
							bigbomb = CCSprite::create(cache->spriteFrameByName("booom_01.png"));
							float s = (float)kBombDisByLevel[current_level]/200.0;
							bigbomb->setScale(s);
							bigbomb->setPosition(temp);
							addChild(bigbomb);
							CCAnimate *bigbombanimate = getBigBombAnimation();
							bigbomb->runAction(CCSequence::create(bigbombanimate,CCCallFuncND::create(this,callfuncND_selector(GamePage::bigBombCallBack),&samecount),NULL));
							isfirstBooom = false;
						}
						else if (samecount>=5&&isfirstLighting)
						{
							CCSprite *lighting;
							b2Body * btemp = getRandomBody();
							//此处矩形的orgin在左下点
							lightrect.setRect(0,btemp->GetPosition().y*PTM_RATIO-50,kLightWidthByLevel[current_level],100);

							lighting = CCSprite::create(cache->spriteFrameByName("D_01.png"));
							lighting->setScaleX((float)kLightWidthByLevel[current_level]/480.0);
							lighting->setPosition(ccp(240,btemp->GetPosition().y*PTM_RATIO));
							addChild(lighting);
							CCAnimate *lightinganimate = getLightingAnimation();
							lighting->runAction(CCSequence::create(lightinganimate,CCCallFuncND::create(this,callfuncND_selector(GamePage::bigBombCallBack),&samecount),NULL));

							isfirstLighting = false;

						}
						if (cs->islock)
						{
							cs->islock = false;
							
							removeChild(cs->lock,true);
						}
						else{
							vector<b2Body*>::iterator it = find(needdelebody.begin(),needdelebody.end(),can_line_list[i]);
							if(it == needdelebody.end())
								needdelebody.push_back(can_line_list[i]);
							//this->removeChild(cs->sp,true);
							//world->DestroyBody(can_line_list[i]);
						}
						
					}
					if (!isfirstBooom)
					{
						temp.x/=PTM_RATIO;
						temp.y/=PTM_RATIO;
						clearBodyAroundPoint(temp,kBombDisByLevel[current_level]/PTM_RATIO);
					}
					if (!isfirstLighting)
					{

						clearBodyInRect(lightrect);
					}
					
				}
				//setScoreByCount(samecount);	
				samecount = 1;
				endpos++;
				startpos = endpos;
				
			}
		}
	}
	for (vector<b2Body*>::iterator it = needdelebody.begin();it!=needdelebody.end();it++)
	{
		SpiriteData *temp = (SpiriteData *)(*it)->GetUserData();
		this->removeChild(temp->sp,true);
		world->DestroyBody(*it);

	}
	for (vector<CCSprite *>::iterator it = spritelist.begin();it!=spritelist.end();it++)
	{
		removeChild(*it,true);
	}
	can_line_list.clear();
	spritelist.clear();
	//pointlist.clear();
	m_pTarget->clear(0,0,0,0);
	needdelebody.clear();
}
b2Body* GamePage::getRandomBody()
{
	
	int num = 0;
	for (b2Body *b = world->GetBodyList();b;b = b->GetNext())
	{
		if (b->GetUserData()!=NULL)
		{
			num++;
		}	
	}

	int pos = rand()%num;
	for (b2Body *b = world->GetBodyList();b;b = b->GetNext())
	{
		if (b->GetUserData()!=NULL)
		{
			if (pos ==0)
			{
				return b;
			}
			pos--;
		}
	}
	return NULL;
}
void GamePage::clearBodyAroundPoint(cocos2d::CCPoint pt,int m_radius)
{
	b2Body *node = world->GetBodyList();
	while (node)
	{
		b2Body *b = node;
		node = node->GetNext();//这样写的原因是当你销毁一个body后，其next会为未知的。
		b2Vec2 temp;
		temp = b->GetPosition();
		int dis=  0;
		dis = sqrt((pt.x-temp.x)*(pt.x-temp.x)+(pt.y-temp.y)*(pt.y-temp.y));
		if(dis<m_radius)
		{
			SpiriteData *spd = (SpiriteData *)(b->GetUserData());
			if (!spd)
			{
				return;
			}
			if (spd&&spd->islock == false)//防止其他静态物体
			{
				vector<b2Body*>::iterator it = find(needdelebody.begin(),needdelebody.end(),b);
				if(it == needdelebody.end())
					needdelebody.push_back(b);
				//this->removeChild(spd->sp,true);
				//world->DestroyBody(b);
			}
			if (spd->islock)
			{
				spd->islock = false;
				removeChild(spd->lock,true);
			}

		}
	}
}

void GamePage::clearBodyInRect(cocos2d::CCRect rc)
{
	b2Body *node = world->GetBodyList();
	while (node)
	{
		b2Body *b = node;
		node = node->GetNext();//这样写的原因是当你销毁一个body后，其next会为未知的。
		CCPoint temp;
		temp.x = b->GetPosition().x*PTM_RATIO;
		temp.y = b->GetPosition().y*PTM_RATIO;

		bool isinrect = CCRect::CCRectContainsPoint(rc,temp);
		if(isinrect)
		{
			SpiriteData *spd = (SpiriteData *)(b->GetUserData());
			if (spd&&spd->islock == false)//防止其他静态物体
			{
				vector<b2Body*>::iterator it = find(needdelebody.begin(),needdelebody.end(),b);
				if(it == needdelebody.end())
					needdelebody.push_back(b);
				//this->removeChild(spd->sp,true);
				//world->DestroyBody(b);
			}
			if (spd->islock)
			{

				spd->islock = false;
				removeChild(spd->lock,true);
			}
		}
	}
}
void GamePage::draw()
{
	CCLayer::draw();
	//用来画出线
	ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );

	kmGLPushMatrix();
	//world->DrawDebugData();
	kmGLPopMatrix();
}
void GamePage::initTimeBar()
{
	CCSprite *timerspirit = CCSprite::create("timeBar.png");
	timerspirit->setScaleX(scaleX);
	timerspirit->setScaleY(scaleY);
	timer = CCProgressTimer::create(timerspirit);
	timer->setScaleX(scaleX);
	timer->setScaleY(scaleY);
	timer->setType(kCCProgressTimerTypeBar);
	timer->setMidpoint(ccp(0,0));
	timer->setBarChangeRate(ccp(1,0));
	timer->setPosition(ccp(240*scaleX,700*scaleY));
	//timer->setScaleX(bgscalex);
	//timer->setScaleY(bgscaley);
	//addChild(timer,-1);
	current_timer_percentage_ = 100;
	speed_of_timer = 0.05;
	//schedule(schedule_selector(GamePage::step),speed_of_timer);

}
void GamePage::step(float ft)
{
	current_timer_percentage_-=0.1;
	if (current_timer_percentage_<=0)
	{
		CCLayerColor *loselayer = CCLayerColor::create(ccc4(0,0,0,100));
		loselayer->setPosition(ccp(0,0));
		CCMenuItemImage *restart = CCMenuItemImage::create("down.png","pop.png",this,menu_selector(GamePage::restartGame));
		restart->setPosition(ccp(0,0));
		CCMenu *menu = CCMenu::create();
		menu->addChild(restart);
		addChild(menu);
		addChild(loselayer,2);
		CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
		unschedule(schedule_selector(GamePage::step));
		((CCMenu*)this->getChildByTag(10))->setEnabled(false);
	}
	timer->setPercentage(current_timer_percentage_);
}
CCAnimate* GamePage::getSmallBombAnimation()
{

	CCArray *spriteframe = CCArray::create(6);
	char str[20];
	for (int i = 0;i<6;i++)
	{
		sprintf(str,"boom_0%d.png",i+1);
		CCSpriteFrame *frame = cache->spriteFrameByName(str);
		spriteframe->addObject(frame);
	}
	CCAnimation *animation = CCAnimation::create(spriteframe,0.04);
	CCAnimate *animate = CCAnimate::create(animation);
	return animate;

}
CCAnimate* GamePage::getBigBombAnimation()
{
	CCArray *spriteframe = CCArray::create(10);
	char str[20];
	for (int i = 0;i<10;i++)
	{
		if(i==9)
			sprintf(str,"booom_%d.png",i+1);
		else
			sprintf(str,"booom_0%d.png",i+1);
		CCSpriteFrame *frame = cache->spriteFrameByName(str);
		spriteframe->addObject(frame);
	}
	CCAnimation *animation = CCAnimation::create(spriteframe,0.04);
	CCAnimate *animate = CCAnimate::create(animation);
	return animate;
}
CCAnimate * GamePage::getLightingAnimation()
{
	CCArray *spriteframe = CCArray::create(3);
	char str[20];
	for (int i = 0;i<3;i++)
	{
		sprintf(str,"D_0%d.png",i+1);
		CCSpriteFrame *frame = cache->spriteFrameByName(str);
		spriteframe->addObject(frame);
	}
	CCAnimation *animation = CCAnimation::create(spriteframe,0.04);
	CCAnimate *animate = CCAnimate::create(animation);
	return animate;
}
void GamePage::smallBombCallBack(cocos2d::CCNode *node)
{
	CCSprite * temp = (CCSprite*)node;
	temp->removeFromParentAndCleanup(true);
	char scorevalue[20];
	sprintf(scorevalue,"SCORE:  %d",current_score);
	scorelabel->setString(scorevalue);
	isNextLevel();
}
void GamePage::bigBombCallBack(cocos2d::CCNode *node,void * a)
{
	CCSprite * temp = (CCSprite*)node;
	temp->removeFromParentAndCleanup(true);
	char scorevalue[20];
	sprintf(scorevalue,"SCORE:  %d",current_score);
	scorelabel->setString(scorevalue);
	isNextLevel();
}
void GamePage::lightingCallBack(cocos2d::CCNode *node)
{
	CCSprite * temp = (CCSprite*)node;
	temp->removeFromParentAndCleanup(true);
}
void GamePage::initMenu()
{
	CCMenuItemImage * gaveforce = CCMenuItemImage::create("pop.png","down.png",this,menu_selector(GamePage::gaveforce));
	gaveforce->setPosition(ccp(300*scaleX,20*scaleY));
	gaveforce->setScale(scale);
	CCMenu *menu = CCMenu::create();
	menu->addChild(gaveforce);
	menu->setAnchorPoint(ccp(0,0));
	menu->setPosition(ccp(0,0));

	CCMenuItemImage * jnitest = CCMenuItemImage::create("pop.png","down.png",this,menu_selector(GamePage::jnitestFunc));
	jnitest->setPosition(ccp(100*scaleX,20*scaleY));
	jnitest->setScale(scale);
	menu->addChild(jnitest);
	//menu->setAnchorPoint(ccp(0,0));
	//menu->setPosition(ccp(150*scaleX,20*scaleY));
	addChild(menu,1);

	
}
void GamePage::gaveforce(cocos2d::CCObject *psender)
{
	for(b2Body * b=world->GetBodyList();b;b = b->GetNext())
	{
			vector<MyContact>::iterator pos;
			for (pos = _contactsListener->_contacts.begin();pos!=_contactsListener->_contacts.end();pos++)
			{

				MyContact contacts = *pos;

				for (b2Fixture *f = b->GetFixtureList();f;f = f->GetNext())
				{
					if(f == contacts.fixtureA &&contacts.fixtureB == forcefix|| f == contacts.fixtureB &&contacts.fixtureA == forcefix)
					{
						b2Vec2 force(0,1000);
						b->ApplyLinearImpulse(force,b->GetPosition());
					}
					
				}
			}

	}
}
void GamePage::initForceRegin()
{
	b2BodyDef forceregin;
	b2Body *forcebody = world->CreateBody(&forceregin);
	b2PolygonShape forceshape;
	forceshape.SetAsBox(100.0*scaleX/PTM_RATIO,30.0*scaleY/PTM_RATIO,b2Vec2(240.0*scaleX/PTM_RATIO,40.0*scaleY/PTM_RATIO),0);
	b2FixtureDef forcefixdef;
	forcefixdef.shape  = &forceshape;
	forcefix = forcebody->CreateFixture(&forcefixdef);
	forcefix->SetSensor(true);
}
void GamePage::restartGame(CCObject *psender)
{
	CCDirector::sharedDirector()->replaceScene(GamePage::scene());
}
void GamePage::lineTwoPoint(cocos2d::CCPoint start,cocos2d::CCPoint end)
{
	if(start.x>end.x)
	{
		CCPoint temp;
		temp = start;
		start = end;
		end = temp;
	}
	float dis = sqrt(abs(start.x-end.x)*abs(start.x-end.x)+abs(start.y-end.y)*abs(start.y-end.y));
	float scaleline = dis/120;
	CCSprite *line = CCSprite::create("bone.png");
	line->setScaleX(scaleline);
	CCPoint midpoint;
	midpoint.x = (start.x+end.x)/2;
	midpoint.y = (start.y+end.y)/2;
	float angle =atan(abs(start.y-end.y)/abs(start.x-end.x));
	
	if(start.y-end.y>0)
		line->setRotation(angle/(2*M_PI)*360);
	else
		line->setRotation(-angle/(2*M_PI)*360);
		line->setPosition(midpoint);
	addChild(line);
	spritelist.push_back(line);


}
void GamePage::setScoreByCount(int count)
{
	if (count<=2)
	{
		return;
	}
	switch (count)
	{
	case 3:
		current_score += kClearThreeScore;
		break;
	case 4:
		current_score += kClearFourScore;
		break;
	case 5:
		current_score += kClearFiveScore;
		break;
	case 6:
		current_score += kClearSixUp;
		break;
	default:
		current_score += kClearSixUp;
		break;
	}

	
}
bool GamePage::isNextLevel()
{
	float percentage;
	switch(current_level)
	{
	case 0:
		percentage = current_score/(float)kLevel1NeedScore*100.0;
		break;
	case 1:
		percentage = current_score/(float)kLevel2NeedScore*100.0;
		break;
	case 2:
		percentage = current_score/(float)kLevel3NeedScore*100.0;
		break;
	default:
		return true;
		break;
	}
	if (percentage>=100)
	{
		current_level++;
		current_score = 0;
		//setLevelLabel();
		showNextLevel();
		return true;
	}
	scorebar->setPercentage(percentage);
	return false;
}
void GamePage::showNextLevel()
{
	unschedule(schedule_selector(GamePage::initByTime));
	touchable = false;
	CCLayerColor *next_layer = CCLayerColor::create(ccc4(0,0,0,100));

	CCSprite *next = CCSprite::create("upgrage.png");
	next->setPosition(ccp(240*scaleX,500*scaleY));
	next->setScale(scale);
	next_layer->addChild(next);

	CCSprite *next_sprite = CCSprite::create("next.png");
	CCSprite *next_click_sprite = CCSprite::create("next.png");

	CCMenuItemSprite *agin = CCMenuItemSprite::create(next_sprite,next_click_sprite,this,menu_selector(GamePage::next));
	agin->setPosition(ccp(0*scaleX,-150*scaleY));
	agin->setScale(scale*0.5);
	CCMenu *menu = CCMenu::create();
	menu->addChild(agin);
	next_layer->addChild(menu);
	addChild(next_layer);
	
}
void GamePage::next(cocos2d::CCObject *sender)
{
	CCDirector::sharedDirector()->replaceScene(GamePage::scene());
}
void GamePage::setLevelLabel()
{
	char levelvalue[5];
	sprintf(levelvalue,"%d",current_level);
	levellabel->setString(levelvalue);



	const char *addr = "192.168.1.1";


}

void GamePage::jnitestFunc(cocos2d::CCObject *psender)
{
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	{
		const char *message = "hello,I am gaoteng";
		int argint = 7;
		JniMethodInfo minfo;

		

		bool isHave = JniHelper::getStaticMethodInfo(minfo,
                                                "com/box2d/colorball/colorball",  //类的路径
                                                "showMessageFromNative",   //方法名
                                                "(Ljava/lang/String;)V"); 
		//jobject jobj;
		jstring StringArg = minfo.env->NewStringUTF(message);
		//minfo.env->GetStringUTFChars();
		 if (isHave) {
			 minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID,StringArg);
		 }
		 CCLog("正确获发送消息");
		
		
		
		
		/*isHave  = JniHelper::getMethodInfo(minfo,
			"com/box2d/colorball/colorball",
			"show",
			"(I)I");
		if (isHave)
		{
			char mess[20];
			
			CCLog("the showMessage method is exits");
			jstring StringArg = minfo.env->NewStringUTF(message);
			jint re = minfo.env->CallIntMethod(jobj, minfo.methodID, argint);
			sprintf(mess,"result is %d",re);
			CCLog(mess);
			}
			else
			{
			CCLog("the showMessage method is not exits");
			}*/
	}
#endif



}